package com.guodi.model.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 戴伙进
 * @time 2018/7/11 11:54
 * @function
 */
public class ByteToFileUtils {
    private static Logger logger = LoggerFactory.getLogger(com.guodi.model.utils.ByteToFileUtils.class);

    /**
     * <p>将文件转成base64 字符串</p>
     *
     * @param path 文件路径
     * @return
     * @throws Exception
     */
    public static String encodeBase64File(String path) throws Exception {
        InputStream inputStream = null;
        byte[] data = null;
        inputStream = new FileInputStream(path);
        data = new byte[inputStream.available()];
        inputStream.read(data);
        inputStream.close();
        //加密
        String result = new String(Base64.getEncoder().encode(data));
        return result;
    }

    /**
     * <p>将base64字符解码保存文件</p>
     *
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */
    public static void decoderBase64File(String base64Code, String targetPath) throws Exception {
        // 获取文件的父路径字符串
        File file = new File(targetPath);
        File path = file.getParentFile();
        createParentDir(path);
        byte[] buffer = Base64.getDecoder().decode(base64Code);
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }

    /**
     * <p>将base64字符保存文本文件</p>
     *
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */
    public static Map<String, Object> Base64ToFile(String base64Code, String targetPath) {
        Map<String, Object> map = new HashMap<>();
        // 获取文件的父路径字符串
        File file = new File(targetPath);
        File path = file.getParentFile();
        FileOutputStream out = null;
        createParentDir(path);
        try {
            byte[] buffer = Base64.getDecoder().decode(base64Code);
            out = new FileOutputStream(targetPath);
            out.write(buffer);
            out.close();
            logger.info("文件保存成功。path={}", path);
            map.put("ok", true);
            map.put("msg", "文件保存成功。path=" + path);
            return map;
        } catch (Exception e) {
            logger.error("文件保存失败。原因：" + e.getMessage());
            map.put("ok", false);
            map.put("msg", "文件保存失败。" + e.getMessage());
            return map;
        }
    }

    /**
     * @描述:创建文件文件夹
     * @入参:
     * @出参:
     * @作者: 戴伙进
     * @日期: 2020/5/24 15:05
     **/
    public static void createParentDir(File path) {
        if (!path.exists()) {
            logger.info("文件夹不存在，创建。path={}", path);
            boolean isCreated = path.mkdirs();
            if (!isCreated) {
                logger.error("创建文件夹失败，path={}", path);
            }
        }
    }

}